package com.bussiness.system.config;

import com.bussiness.system.jwt.JWT;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @Author: xlr
 * @Date: Created in 下午11:46 2018/8/29
 */
public class InterceptorConfig implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(InterceptorConfig.class);


    @Autowired
    JWT jwt;

    /**
     * 进入controller层之前拦截请求
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        log.info("---------------------开始进入请求地址拦截----------------------------");
        String tonken = httpServletRequest.getHeader( "Authorization");
        if(StringUtils.isNotBlank( tonken )){
            //校验token
            Claims claims = jwt.getClaimByToken( tonken );
            //用户ID
            String userId = claims.getSubject();
            //过期时间
            Date endDate = claims.getExpiration();
            //签发时间
            Date startDate = claims.getIssuedAt();
            boolean flag = jwt.isTokenExpired( new Date(  ) );
            if(!flag){
                PrintWriter printWriter = httpServletResponse.getWriter();
                printWriter.write("{code:0,message:\"token is invalid,please login again!\"}");
                return false;
            }
            return true;
        } else{
            PrintWriter printWriter = httpServletResponse.getWriter();
            printWriter.write("{code:0,message:\"token is invalid,please login again!\"}");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("---------------视图渲染之后的操作-------------------------0");
    }

}
